import Taro from "@tarojs/taro";
import { useBoolean } from "ahooks";
import { Image, Input, Navigator, Text, View } from "@tarojs/components";
import ByCheckbox from "@/components/ui/ByCheckbox";
import ByButton from "@/components/ui/ByButton";
import ByIcon from "@/components/ui/ByIcon";

import useForm from "@/hooks/useForm";
import ApiUser from "@/api/user";
import { getUserInfo } from "@/api/login";

import { ACCESSTOKEN } from "@/utils/constant";

import "./index.less";
import useAppStore from "@/store";

// 13590488838
// Sa1230

const validator = (_, value, callback) => {
  if (value.trim()) {
    callback();
    return;
  }

  callback(new Error());
};

export default () => {
  // 是否正在尝试静默登录
  const logginIn = useAppStore((state) => state.appLoggingIn);

  // 是否已勾选协议
  const [checked, { toggle }] = useBoolean();

  // 表单
  const { model, loading, setModel, submit } = useForm(ApiUser.login, {
    tokenAuth: false,
    rules: {
      username: [
        { required: true, message: "请输入账号" },
        { validator, message: "请输入正确的账号" },
      ],
      password: { required: true, message: "请输入密码" },
    },
    onSuccess(res) {
      Taro.setStorageSync(ACCESSTOKEN, res.accessToken);

      getUserInfo();

      Taro.showToast({
        icon: "success",
        title: "登录成功",
      });

      setTimeout(() => {
        Taro.reLaunch({ url: "/pages/index/index" });
      }, 1500);
    },
  });

  const handleTap = async () => {
    if (!checked) {
      Taro.showToast({ icon: "none", title: "您需阅读并同意隐私服务协议" });
      return;
    }

    const { code } = await Taro.login();
    // 不需要更新试图
    model.code = code;
    submit();
  };

  return logginIn ? (
    <View className="h-screen flex-center">
      <View className="relative -mt-[200px]">
        <View className="loading-spiner" />

        <View className="relative text-center h-full flex-center">
          <Image
            src="/static/images/logo.png"
            className="w-[140px] h-[140px]"
          />
        </View>
      </View>
    </View>
  ) : (
    <>
      <View className="fixed top-0 rounded-full ball" />
      <View className="fixed top-0 rounded-full ball2" />
      <View className="relative">
        <View className="mt-[120px] text-center mb-10">
          <Image
            src="/static/images/login-logo.png"
            className="w-[460px]"
            mode="widthFix"
          />
        </View>

        <View className="mt-10 text-center w-full relative">
          <View className="mt-[120px] px-10">
            <View className="flex mb-3 px-4 items-center bg-page rounded-full">
              <ByIcon name="User" size={38} />
              <Input
                alwaysEmbed
                // @ts-expect-error
                autocomplete="off"
                value={model.username}
                className="flex-auto h-[100px] text-lg"
                placeholder="输入账号"
                onInput={(e) => setModel({ username: e.detail.value })}
              />
            </View>

            <View className="overflow-hidden h-[0]">
              <Input disabled />
            </View>

            <View className="flex px-4 items-center mb-10 bg-page rounded-full">
              <ByIcon name="Lock" size={38} />
              <Input
                value={model.password}
                className={`flex-auto h-[100px] ${
                  model.password ? "text-[56px]" : "text-lg"
                } `}
                placeholder="输入密码"
                password
                alwaysEmbed
                // @ts-expect-error
                autocomplete="off"
                onInput={(e) => setModel({ password: e.detail.value })}
              />
            </View>

            <ByButton
              size="large"
              loading={loading || logginIn}
              onClick={handleTap}
            >
              登录
            </ByButton>
          </View>

          <View className="flex-center py-3 mt-3">
            <ByCheckbox
              className="text-second text-sm"
              checked={checked}
              onChange={toggle}
            >
              <View className="flex ml-1">
                <Text>我已阅读并同意</Text>
              </View>
            </ByCheckbox>
            <Navigator
              className="underline text-second text-sm"
              url={`agreement`}
            >
              隐私服务协议
            </Navigator>

            <View className="safe-footer" />
          </View>
        </View>
      </View>
    </>
  );
};
